/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pocketsweet.chatui;

import java.util.Map;

import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.OnMessageNotifyListener;
import com.easemob.chat.OnNotificationClickListener;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.ChatActivity;
import com.pocketsweet.chatlib.controller.HXSDKHelper;
import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.chatui.receiver.CallReceiver;
import com.pocketsweet.chatui.utils.CommonUtils;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.NewApply;
import com.pocketsweet.ui.NewLover;

/**
 * Demo UI HX SDK helper class which subclass HXSDKHelper
 * 
 * @author easemob
 * 
 */
public class MLHXSDKHelper extends HXSDKHelper {

	/**
	 * contact list in cache
	 */
	private Map<String, User> contactList;
	private Map<String, User> strangerList;
	private CallReceiver callReceiver;

	@Override
	protected void initHXOptions() {
		super.initHXOptions();
		// you can also get EMChatOptions to set related SDK options
		// EMChatOptions options = EMChatManager.getInstance().getChatOptions();
	}

	@Override
	protected OnMessageNotifyListener getMessageNotifyListener() {
		// 取消注释，app在后台，有新消息来时，状态栏的消息提示换成自己写的
		return new OnMessageNotifyListener() {

			@Override
			public String onNewMessageNotify(EMMessage message) {
				// 设置状态栏的消息提示，可以根据message的类型做相应提示
				String ticker = CommonUtils.getMessageDigest(message,
						appContext);
				// Log.e("收到消息", ticker);
				if (message.getType() == Type.TXT)
					ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
				String nickname = MLCache.getNickById(message.getFrom());
				return nickname + ": " + ticker;
			}

			@Override
			public String onLatestMessageNotify(EMMessage message,
					int fromUsersNum, int messageNum) {
				return fromUsersNum + "个恋人，发来了" + messageNum + "条消息";
			}

			@Override
			public String onSetNotificationTitle(EMMessage message) {
				// 修改标题,这里使用默认
				return null;
			}

			@Override
			public int onSetSmallIcon(EMMessage message) {
				// 设置小图标
				return R.drawable.ic_launcher;
			}
		};
	}

	@Override
	protected OnNotificationClickListener getNotificationClickListener() {
		return new OnNotificationClickListener() {

			@Override
			public Intent onNotificationClick(EMMessage message) {
				// if (message.getFrom().equals(Constant.NEW_CHAT_APPLY)) {
				// Intent intent = new Intent(appContext, NewApply.class);
				// return intent;
				// } else
				if (message.getFrom().equals(Constant.NEW_FRIENDS_USERNAME)) {
					Intent intent = new Intent(appContext, NewLover.class);
					return intent;
				}
				Intent intent = new Intent(appContext, ChatActivity.class);
				ChatType chatType = message.getChatType();
				if (chatType == ChatType.Chat) { // 单聊信息
					String from = message.getFrom();

					intent.putExtra("userId", from);
					intent.putExtra("nickName", MLCache.getNickById(from));
					intent.putExtra("avatar", MLCache.getAvatarById(from));
				}
				return intent;
			}
		};
	}

	@Override
	protected void onConnectionConflict() {
		MLApplication.getInstance().isLogin = true;
		Intent intent = new Intent(appContext, Main.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("conflict", true);
		appContext.startActivity(intent);
	}

	@Override
	protected void onCurrentAccountRemoved() {
		MLApplication.getInstance().isLogin = true;
		Intent intent = new Intent(appContext, Main.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra(Constant.ACCOUNT_REMOVED, true);
		appContext.startActivity(intent);
	}

	@Override
	protected void initListener() {
		super.initListener();
		IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance()
				.getIncomingCallBroadcastAction());
		if (callReceiver == null)
			callReceiver = new CallReceiver();
		appContext.registerReceiver(callReceiver, callFilter);
	}

	@Override
	protected MLHXSDKModel createModel() {
		return new MLHXSDKModel(appContext);
	}

	/**
	 * get demo HX SDK Model
	 */
	public MLHXSDKModel getModel() {
		return (MLHXSDKModel) hxModel;
	}

	@Override
	public void logout(final EMCallBack callback) {
		endCall();
		super.logout(new EMCallBack() {

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				getModel().closeDB();
				if (callback != null) {
					callback.onSuccess();
				}
			}

			@Override
			public void onError(int code, String message) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgress(int progress, String status) {
				// TODO Auto-generated method stub
				if (callback != null) {
					callback.onProgress(progress, status);
				}
			}

		});
	}

	void endCall() {
		try {
			EMChatManager.getInstance().endCall();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
